using System;
using System.Collections.Generic;
using System.Reflection;
using DMS.BEs;

namespace DMS.DAOs.Memory
{
	public abstract class AbstractDAO<T> where T : Persistent
	{
		private static readonly IDictionary<int, T> table;

		static AbstractDAO()
		{
			table = new Dictionary<int, T>();
		}

		protected ICollection<T> Entities
		{
			get { return table.Values; }
		}

		public T GetById(int id)
		{
			T entity;
			return table.TryGetValue(id, out entity) ? entity : default(T);
		}

		public void Persist(T entity)
		{
			if (entity.Id != 0 && table.ContainsKey(entity.Id))
				return;

			ManagerIds.SetId(entity);

			table.Add(entity.Id, entity);
		}

		public void Delete(T entity)
		{
			table.Remove(entity.Id);
		}

		public ICollection<T> GetAll()
		{
			return Entities;
		}
	}
}